---
type Props = {
  label: string;
  href?: string;
  open?: string;
  clickIdentifier?: string;
  parent?: string;
};

const { label, href, open, clickIdentifier, parent } = Astro.props;

let labelIcon = '';

if (Astro.slots.has('label-icon')) {
  labelIcon = await Astro.slots.render('label-icon');
}

const isDevMode = import.meta.env.DEV;
---

<script is:inline define:vars={{ label, href, open, clickIdentifier, labelIcon, isDevMode, parent }}>
  const parentElement = document.currentScript.parentElement;

  // We used a web component in the `<UserButton.MenuItems>` component.
  const hasParentMenuItem = parentElement.tagName.toLowerCase() === 'clerk-user-button-menu-items';
  if (!hasParentMenuItem) {
    if (isDevMode) {
      throw new Error(
        `Clerk: <UserButton.MenuItems /> component can only accept <UserButton.Action /> and <UserButton.Link /> as its children. Any other provided component will be ignored.`,
      );
    }
    return;
  }

  // Get the user button map from window that we set in the `<InternalUIComponentRenderer />`.
  const userButtonComponentMap = window.__astro_clerk_component_props.get('user-button');

  let userButton;
  if (parent) {
    userButton = document.querySelector(`[data-clerk-id="clerk-user-button-${parent}"]`);
  } else {
    userButton = document.querySelector('[data-clerk-id^="clerk-user-button"]');
  }

  const safeId = userButton.getAttribute('data-clerk-id');
  const currentOptions = userButtonComponentMap.get(safeId);

  const reorderItemsLabels = ['manageAccount', 'signOut'];
  const isReorderItem = reorderItemsLabels.includes(label);

  let newMenuItem = {
    label,
  };

  if (!isReorderItem) {
    newMenuItem = {
      ...newMenuItem,
      mountIcon: el => {
        el.innerHTML = labelIcon;
      },
      unmountIcon: () => {
        /* What to clean up? */
      },
    };

    if (href) {
      newMenuItem.href = href;
    } else if (open) {
      newMenuItem.open = open.startsWith('/') ? open : `/${open}`;
    } else if (clickIdentifier) {
      const clickEvent = new CustomEvent('clerk:menu-item-click', { detail: clickIdentifier });
      newMenuItem.onClick = () => {
        document.dispatchEvent(clickEvent);
      };
    }
  }

  userButtonComponentMap.set(safeId, {
    ...currentOptions,
    customMenuItems: [...(currentOptions?.customMenuItems ?? []), newMenuItem],
  });
</script>
